package net.chrisrichardson.ec2deployer.applications

import net.chrisrichardson.ec2deployer.core.Metric;

def class JmeterLogAnalyzer {

    def path
    def timings = new HashMap()
    def startTime
    def endTime
    def transactionCount = 0

    JmeterLogAnalyzer(String path) {
        this.path = path;
     }

     def analyze() {
        File f = new File(path)

        startTime = Long.MAX_VALUE
        endTime = 0

        f.eachLine{processLine(it)}
     }

     def processLine(line) {
        def elements = line.split(',')
        def timing = Integer.parseInt(elements[1])
        def request = elements[2]
        def statusString = elements[3]
        def status = statusString.size() > 3 ? - 1: Integer.parseInt(statusString)

        def metric = timings[request]


        if (!metric) {
            metric = new Metric()
            timings[request] = metric
        }

        metric << [timing, status]

        startTime = Math.min(startTime, Long.parseLong(elements[0]))
        endTime = Math.max(endTime, Long.parseLong(elements[0]))
        transactionCount++

        elements
      }

      def report(String path, hosts, cpuCount, threadCount) {
       def builder = new groovy.xml.MarkupBuilder(new OutputStreamWriter(new FileOutputStream(path)))  // TODO close me
       builder.performanceReport {
         cpus cpuCount
         threads threadCount
         hosts.entrySet().each { hostEntry ->
           host {
             name hostEntry.key
             cpuUtil hostEntry.value.getAverageBusy()
           }
         }
         requests {
             timings.entrySet().sort{ a, b-> a.key <=> b.key}.each{ pair ->
                request {
                  name pair.key
                  art pair.value.average()
                  errors pair.value.errorPercentage()
                }
             }
         }
         def durationValue = ((float)(endTime - startTime))/1000.0
         duration durationValue
         def tpsValue = transactionCount/ durationValue
         tps tpsValue
         art averageResponseTime()
       }
      }

      def averageResponseTime() {
          def count = 0
          def total = 0

          timings.values().each{count += it.count; total += it.sum}

          total/count
      }
}

